package com.itheima.reggie.conrtroller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;


    //登录方法
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //将页面提交的密码进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //根据页面提交的用户名查询数据库
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        //将获取的用户名交给wrapper，此时wrapper有一个用户名为传进来的username的条件
        wrapper.eq(Employee::getUsername, employee.getUsername());
        //根据wrapper里面的条件查询出一个对象
        Employee one = employeeService.getOne(wrapper);
        //如果返回的对象为null，说明数据库没有查询到这个用户名，返回登陆失败结果
        if (one == null) {
            return R.error("登录失败");
        }
        //密码对比，如果不一致则返回登陆失败结果
        if (!one.getPassword().equals(password)) {
            return R.error("登录失败");
        }
        //查询员工状态，如果返回值为0则表示账号已禁用，返回账号已禁用结果
        if (one.getStatus() == 0) {
            return R.error("账号已禁用");
        }

        //如果上述条件都不成立，则登录成功，将员工id存入session域中（cookie保存账号），并返回登录成功结果
        request.getSession().setAttribute("employee", one.getId());
        return R.success(one);
    }


    //退出方法
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //清理Session中保存的当前登录员工id,从域里面移除
        request.getSession().removeAttribute("employee");
        //给前端返回一个退出成功结果
        return R.success("退出成功");
    }

    //新增方法
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增员工信息：{}", employee.toString());
        //设置初始密码为123456，并进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置创建和修改时间为当前时间
      /*  employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //获取当前登录员工的id,并传入employee对象
        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(empId);
        employee.setCreateUser(empId);*/
        //调用save（因为EmployeeService继承了IService,又因为EmployeeServiceImpl继承了ServiceImpl并）方法

        employeeService.save(employee);
        return R.success("添加成功");
    }


    //分页查询方法
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page={},pageSize={},name={}", page, pageSize, name);
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加排序条件
        wrapper.orderByDesc(Employee::getId);
        //分页查询
        employeeService.page(pageInfo, wrapper);
        return R.success(pageInfo);
    }

    //启用禁用账户方法
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
        log.info(employee.toString());
        /*//获取当前登录员工的id,并传入employee对象
       *//* Long o = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(o);
        employee.setUpdateTime(LocalDateTime.now());*/
        employeeService.updateById(employee);
        return R.success("员工信息修改成功");
    }

    //根据id查询员工
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        log.info("根据id查询员工信息");
        //查询
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没找到对应员工");
    }

}
